package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.AdminDao;
import dao.AnnounceDao;
import dao.UserDao;
import dao.impl.AdminDaoImpl;
import dao.impl.UserDaoImpl;
import model.Admin;
import model.User;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/AdminServlet")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("utf-8");
		String action = request.getParameter("action");	
			try {
				if(action.equals("register")) {
					register(request,response);
				}if(action.equals("login")) {
					login(request,response);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}		
	}
	//管理员登录
	private void login(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
		//得到前端页面表单中的信息
		String name = (String) request.getParameter("user");
		String pwd = (String) request.getParameter("pass");
		//创建数据访问对象
		AdminDao ad = new AdminDaoImpl();
		Admin admin =ad.getAdminByIdAndPwd(name, pwd);
		if(admin != null) {
			HttpSession session = request.getSession();
			session.setAttribute("logoner", admin);
			response.sendRedirect("admin_pages/admin.jsp");
		}else {
			response.sendRedirect("admin_pages/logon.jsp");
		}
		
	}

	//管理员注册
	private void register(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
		//得到前端页面的注册信息
		String id = request.getParameter("email");
		String name = request.getParameter("username");
		String sex = request.getParameter("sex");
		String pwd1 = request.getParameter("password");
		String phone = request.getParameter("phone");
		//创建数据访问对象
		AdminDao ad = new AdminDaoImpl();
		boolean admin =  ad.register(id,name,sex,pwd1,phone);
		if(admin) {
			response.sendRedirect("admin_pages/logon.jsp");
		}else {
			response.sendRedirect("admin_pages/register.jsp");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
